package com.lovo.sqlatm;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Transfer extends JPanel implements ActionListener {
    private Test0 frame;
    private JTextField counterpartAccount = new JTextField();
    private JTextField TransferMoney = new JTextField();

    private Icon conImage = Util.getIcon("/img/buttonSure.jpg");
    private Icon cancelImage = Util.getIcon("/img/buttonOff.jpg");
    private JButton confirmButton;
    private JButton cancelButton;

    public Transfer(Test0 frame) {
        this.frame = frame;
        this.setLayout(null);
        JLabel counterpartAccountText = new JLabel("请输入对方账号：");
        counterpartAccountText.setBounds(314, 238, 160, 40);
        this.add(counterpartAccountText);

        JLabel TransferMoneyText = new JLabel("请输入转账金额：");
        TransferMoneyText.setBounds(314, 300, 160, 40);
        this.add(TransferMoneyText);
// 对方账号输入
        counterpartAccount.setBounds(454, 238, 160, 40);
        this.add(counterpartAccount);
        counterpartAccount.getText();
//转账金额输入
        TransferMoney.setBounds(454, 300, 160, 40);
        this.add(TransferMoney);
        TransferMoney.getText();

        //确认按钮
        confirmButton = new JButton(conImage);
        confirmButton.setBounds(354, 400, 140, 50);
        confirmButton.addActionListener(this);
        this.add(confirmButton);
        //返回按钮
        cancelButton = new JButton(cancelImage);
        cancelButton.setBounds(540, 400, 140, 50);
        this.add(cancelButton);
        cancelButton.addActionListener(this);


        this.setOpaque(false);
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == confirmButton) {
            String counterpartUse = counterpartAccount.getText();
            int money = Integer.parseInt(TransferMoney.getText());
            if (counterpartUse.equals(frame.getUesr().getAccount())) {
                JOptionPane.showMessageDialog(this, "不能转给自己");
                return;
            }
            if (money > frame.getUesr().getBalance()) {
                JOptionPane.showMessageDialog(this, "余额不足");
                return;
            }
                    //确认当前用户和转帐用户
            JdbcUtil jdbcUtil =new JdbcUtil();
            Uesr loginUser = jdbcUtil.selectId(frame.getUesr().getId());
            Uesr otherUser = jdbcUtil.selectName(counterpartUse);

            //用户的余额加减
            loginUser.setBalance(loginUser.getBalance()-money);
            otherUser.setBalance(otherUser.getBalance()+money);
            //通过方法返回到数据库中
            jdbcUtil.update(loginUser,otherUser);


                    JOptionPane.showMessageDialog(this,loginUser.getBalance());
                    return;




        } else if (e.getSource() == cancelButton) {
            frame.switchPanel("menu");
        }

    }
}
